/**
 * @author Chad Dettmering
 */

package org.flckphoto;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;

import org.xml.sax.SAXException;

import com.aetrion.flickr.FlickrException;
import com.aetrion.flickr.auth.Auth;
import com.aetrion.flickr.auth.AuthInterface;
import com.aetrion.flickr.auth.Permission;

import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;

/**
 * This activity is called when authenticating the user with Flickr
 */
public class AuthenticationActivity extends Activity {
	/**
	 * Tag for log output
	 */
	private static final String TAG = "AuthenticationActivity";
	
	/**
	 * the Flickr "frob" used in authentication
	 */
	private String frob = "";
	
	/**
	 * authentication interface used by Flickr
	 */
	private AuthInterface authInterface;
	
	/**
	 * the url to handle authentication
	 */
	private URL authUrl;
	
	/**
	 * the webview for the auth url
	 */
	private WebView view;
	
	@Override
	/**
	 * This is called when the activity is created
	 */
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		
		//show authentication layout
		setContentView(R.layout.authentication);
		
		if(bundle != null)
			((WebView) findViewById(R.id.authPage)).restoreState(bundle);
		else {
			//try to authenticate
			authUrl = authenticate();
			
			//authentication failed
			if(authUrl == null) {
				Log.e(TAG,"Authentication failure");
				setResult(Activity.RESULT_CANCELED);
				finish();
			}
			
			//create webview and button
			view = (WebView) findViewById(R.id.authPage);
			
			//ensure that the webview holds all the pages
			view.setWebViewClient(new FlickrWebViewClient());
			
			//enable javascript and plugins
			WebSettings settings = view.getSettings();
			settings.setJavaScriptEnabled(true);
			settings.setPluginsEnabled(true);
			
			//load the auth url
			view.loadUrl(authUrl.toExternalForm());
		}
		
		//setup the button
		Button b = (Button) findViewById(R.id.doneButton);
		b.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				Auth auth = finishAuth();
				//if auth failed, record in log and set result to bad
				if(auth == null)
				{
					Log.e(TAG, "Authentication interface could not be obtained");
					FlickrManager.getSingleton().setAuthInterface(null);
					setResult(Activity.RESULT_CANCELED);
					finish();
				}
				//auth succeeded
				else
				{
					Log.d(TAG, "Authentication succeeded");
					FlickrManager.getSingleton().setAuthInterface(auth);
					setResult(Activity.RESULT_OK);
					finish();
				}
			}
		});
	}
	
	/**
	 * Tries to authenticate the application with Flickr
	 * @return an Auth handle if authenticated, null if not authenticated
	 */
	private URL authenticate(){
		URL authUrl = null;
		try {
			Log.d(TAG, "Obtaining authentication interface");
			//get authentication interface
			authInterface = FlickrManager.getSingleton()
											.getFlickrInterface().getAuthInterface();
			
			//create the "frob"
			frob = authInterface.getFrob();
			
			Log.d(TAG, "Building authentication URL");
			//build the URL that will be used for the user to authenticate with
			authUrl = authInterface.buildAuthenticationUrl(Permission.WRITE, frob);
		}
		catch(FlickrException e) {
			Log.e(TAG, e.getMessage());
			authUrl = null;
		}
		catch(SAXException e) {
			Log.e(TAG, e.getMessage());
			authUrl = null;
		}
		catch(IOException e) {
			Log.e(TAG, e.getMessage());
			authUrl = null;
		}
		
		return authUrl;
	}
	
	/**
	 * Completes the authentication process when web browser closes
	 * @return a new Auth object, or null if this method failed
	 */
	private Auth finishAuth() {
		Auth auth = null;
		
		try {
			//try to get the auth token
			auth = authInterface.getToken(frob);
			
			Log.d(TAG, "Checking authentication...");
			auth = authInterface.checkToken(auth.getToken());
			Settings.authToken = auth.getToken();
			Log.d(TAG, "Authentication valid.");
			
			FileInputStream f = openFileInput(Settings.FILENAME);
			Scanner fin = new Scanner(f);
			String user = "";
			String pass = "";
			String auth2 = "";
			if(fin.hasNext()) {
				user = fin.next();
				pass = fin.next();
				auth2 = fin.next();
			}
			else {
				user = "placeholder";
				pass = "placeholder";
				auth2 = "xxxxxx";
			}
			
			auth2 = auth.getToken();
			
			fin.close();
			
			//write the new auth token to settings
			FileOutputStream f2 = openFileOutput(Settings.FILENAME, MODE_PRIVATE);
			String output = user + " " + pass + " " + auth2;
			f2.write(output.getBytes());
			f2.close();
		}
		catch(FlickrException e) {
			Log.e(TAG, e.getMessage());
			auth = null;
		}
		catch(IOException e) {
			Log.e(TAG, e.getMessage());
			auth = null;
		}
		catch(SAXException e) {
			Log.e(TAG, e.getMessage());
			auth = null;
		}
		
		return auth;
	}
	
	@Override
	protected void onSaveInstanceState(Bundle bundle) {
		view.saveState(bundle);
	}

}
